import java.util.Collection;
import java.util.LinkedList;

public class AgentBFS implements Agent {
	
	public AgentBFS()
	{
		
	}
	
	public void init(Collection<String> percepts) {
		
		Map map = new Map(percepts);
		Sucky sucky = new Sucky(percepts);
		
		while(map.containsDirt()) {
			Position prevPos = sucky.getPosition();
			
			sucky = bfs(sucky, map, CellType.Dirty);
			
			if(sucky.getPosition().equals(prevPos)) {
				break;
			}
		}
		sucky = bfs(sucky, map, CellType.Home);
		
		_actions = sucky.getInstructions();
		for(String s : _actions)
			System.out.println(s);
	}
	
	private Sucky bfs(Sucky sucky, Map map, CellType cellTarget) {
		
		LinkedList<Sucky> herd = new LinkedList<Sucky>();
		map.clearVisited();
		map.visit(sucky.getPosition());
		herd.add(sucky);
		
		while(herd.size() > 0) {
			
			Sucky target = herd.pollFirst();
			LinkedList<Direction> directions = target.getAvailableDirections(map);
			
			for(Direction dir : directions) {
				
				Sucky fork = target.forkTo(dir);
				Position pos = fork.getPosition();
				map.visit(pos);
				
				if(map.getAt(pos) == cellTarget)
				{
					sucky = fork.fork(ActionType.Suck);
					map.cleanCellAt(pos);
					return sucky;
				}
				else herd.push(fork);
			}
		}
		return sucky;
	}
	
	private LinkedList<String> _actions;
	private Boolean _givingUp = false;
	
	public String nextAction(Collection<String> percepts) {
		
		if(_actions != null) {
			return _actions.poll();
		}
		else {
			Boolean temp = _givingUp;
			_givingUp = true;
			if(temp) return "TURN_OFF";
			else return "TURN_ON";
		}
	}
}
